package com.futao.springbootlearn20220224.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author futao@gmail.com
 * @date 2022/3/9
 */
@Slf4j
@Configuration
public class AsyncThreadPool implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(4);
        threadPoolTaskExecutor.setMaxPoolSize(8);
        threadPoolTaskExecutor.setKeepAliveSeconds(30);
        threadPoolTaskExecutor.setQueueCapacity(1024);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.setThreadNamePrefix("my-thread-pool-impl-");
        // 需要进行初始化，否则会报错，ThreadPoolTaskExecutor not initialized
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> log.info("异步线程发生异常", ex);
    }

    // @Bean
    // public Executor asyncExecutor() {
    //     ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
    //     threadPoolTaskExecutor.setCorePoolSize(4);
    //     threadPoolTaskExecutor.setMaxPoolSize(8);
    //     threadPoolTaskExecutor.setKeepAliveSeconds(30);
    //     threadPoolTaskExecutor.setQueueCapacity(1024);
    //     threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    //     threadPoolTaskExecutor.setThreadNamePrefix("my-thread-pool-");
    //     return threadPoolTaskExecutor;
    // }
}
